package com.chenyue.cm.controller;

import cn.hutool.core.util.RandomUtil;
import com.chenyue.cm.utils.DateUtils;
import com.chenyue.cm.utils.FileUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author origin
 */
@Controller
public class UploadController {

    @Value("${lcmaster.upload.systemUploadPath}")
    private String systemUploadPath;

    /**
     * 文件上传
     *
     * @param request 请求
     * @return state ：状态  path ：路径
     */
    @RequestMapping("/upload")
    @ResponseBody
    public Map<String, Object> upload(HttpServletRequest request) {

        Map<String, Object> resultMap = new HashMap<>();

        try {

            String dateStr = DateUtils.getTodayStr();

            String descFileDir = systemUploadPath + dateStr;

            FileUtil.mkdirs(descFileDir);

            String dataString = "";

            StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
            Iterator<String> iterator = req.getFileNames();
            while (iterator.hasNext()) {
                MultipartFile file = req.getFile(iterator.next());
				if (file == null) {
					continue;
				}
                String fileNames = file.getOriginalFilename();
//                int split = fileNames.lastIndexOf(".");
                //存储文件
                //文件名  fileNames.substring(0,split)
                //文件格式   fileNames.substring(split+1,fileNames.length())
                //文件内容 file.getBytes()
                //file.getInputStream()
                String newFileName;
                if (StringUtils.isNotBlank(fileNames)) {
                    newFileName = DateUtils.getTodayStr() + RandomUtil.getRandom(true).nextInt(10000) + fileNames.substring(fileNames.lastIndexOf("."));
                }else {
					newFileName = "";
				}

                InputStream is = file.getInputStream();
                byte[] buffer = new byte[1024];
                int len;
                OutputStream out = new FileOutputStream(descFileDir + "/" + newFileName);
                while ((len = is.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                out.close();
                is.close();

                dataString = "/upload/" + dateStr + "/" + newFileName;

            }

            resultMap.put("state", "success");
            resultMap.put("path", dataString);

            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("state", "fail");
        }

        return resultMap;

    }

}
